﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ClientManager.aspx.cs" Inherits="GPSTrackingWebsiteManager.Pages.ClientManager" %>

<!DOCTYPE html>
<link href="../../Css/GPSTrackingWebsite.css" rel="stylesheet" />
<link href="../../Css/messi.css" rel="stylesheet" />
<script src="../../Javascript/jquery-1.11.1.min.js"></script>
<script src="../../Javascript/messi.js"></script>
<script src="../../Javascript/Custom.js"></script>
<script src="../../Javascript/WindowMessageManager.js"></script>
<script src="../../Javascript/ObjectsV2.js"></script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <telerik:RadScriptBlock ID="RadScriptBlock1" runat="server">
        <script type="text/javascript">

            //Windows Message Manager 
            var objWindowsMessageManager = new WindowsMessageManager();

            var opener = GetRadWindow();
            var ClientManager = new ClientManager();
            var Companies = new Companies();

            function GetRadWindow() {
                var oWindow = null;
                if (window.radWindow)
                    oWindow = window.radWindow;
                else if (window.frameElement.radWindow)
                    oWindow = window.frameElement.radWindow;
                return oWindow.BrowserWindow;
            }

            function initializeObjects() {
                opener.globalClientManager.clientMarker = opener.objMapControl.addMarker(null, null, null);
            }

            function clearObjects() {
                ClientManager.hideAllClientsSelected(opener.globalClientManager.clientsList);
                ClientManager.enableDisableClientEventClickMap(opener, false);
            }

            function restorePage() {
                ClientManager.showAllClientsChecked(opener.globalClientManager.clientsList);
                ClientManager.enableDisableClientEventClickMap(opener, getCkbClient().checked);
            }

            function getCompaniesByAdminUsername() {
                initializeObjects();
                PageMethods.wsGetCompaniesByAdminUsername(getCompaniesByAdminUsernameOk, getCompaniesByAdminUsernameError);
            }

            function getCompaniesByAdminUsernameOk(object) {
                //requestStart(getrpvClientManagerUpdateControl());
                Companies.openXMLCompaniesByAdminUsername(object, opener.globalClientManager.companiesList);
                Companies.loadCompaniesDataSource(getCompaniesGrid(), opener.globalClientManager.companiesList, opener.globalClientManager.companiesDataSource);
                if (opener.globalClientManager.companiesList.length == 1) {
                    getCompaniesGrid().selectItem(0);
                    if (ClientManager.isValidToGetClientsGroups(opener, opener.globalClientManager.companiesList[0].companyID, getClientsGroupsGrid())) {
                        //requestStart(getrpvClientManagerUpdateControl());
                        getClientsGroupsByCompanyID();
                    }
                }
                //responseEnd(getrpvClientManagerUpdateControl());
            }

            function getCompaniesByAdminUsernameError(error) {
                responseEnd(getrpvClientManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
            }

            function CompaniesGrid_OnRowClick(sender, args) {
                if (ClientManager.isValidToGetClientsGroups(opener, args.getDataKeyValue("CompanyID"), getClientsGroupsGrid())) {
                    requestStart(getrpvClientManagerUpdateControl());
                    getClientsGroupsByCompanyID();
                }
            }

            function getClientsGroupsByCompanyID() {
                PageMethods.wsGetClientsGroupsByCompanyID(opener.globalClientManager.companyID, getClientsGroupsByCompanyIDOk, getClientsGroupsByCompanyIDError);
            }

            function getClientsGroupsByCompanyIDOk(object) {
                ClientManager.openXMLClientsGroupsByCompanyID(object, opener.globalClientManager.clientsGroupsList);
                loadClientsGroupsDataSourceWait();
                //ClientManager.openXMLClientsByUsernameAndClientGroupID(opener.objMapControl, object, opener.globalClientManager.clientsList);
                //ClientManager.loadClientsDataSource(getClientGrid(), opener.globalClientManager.clientsList, opener.globalClientManager.clientsDataSource);
                responseEnd(getrpvClientManagerUpdateControl());
            }

            function getClientsGroupsByCompanyIDError(error) {
                responseEnd(getrpvClientManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
            }




            function getClientsGroupsGrid() {
                try{
                    return $find("<%= rgClientsGroupsGrid.ClientID %>").get_masterTableView();
                }
                catch(ex){
                    setTimeout(getClientsGroupsGrid, 100);
                }
            }

            function getCompaniesGrid() {
                try {
                    return $find("<%= rgCompaniesGrid.ClientID %>").get_masterTableView();
                }
                catch (ex) {
                    setTimeout(getCompaniesGrid, 100);
                }
            }

            function getClientGrid() {
                try {
                    return $find("<%= rgClientsGrid.ClientID %>").get_masterTableView();
                                }
                catch (ex) {
                    setTimeout(getClientGrid, 100);
                }
            }

            function ClientsGroupsGrid_OnRowClick(sender, args) {
                if (ClientManager.isValidToGetClients(opener, args.getDataKeyValue("ClientGroupID"), getClientGrid())) {
                    requestStart(getrpvClientManagerUpdateControl());
                    getClientsByCompanyAndClientGroupID();
                }
            }


            function getClientsByCompanyAndClientGroupID() {
                PageMethods.wsGetClientsByCompanyIDAndClientGroupID(opener.globalClientManager.companyID, opener.globalClientManager.clientGroupID, getClientsByCompanyAndClientGroupIDOk, getClientsByCompanyAndClientGroupIDError);
            }

            function getClientsByCompanyAndClientGroupIDOk(object) {
                ClientManager.openXMLClientsByCompanyAndClientGroupID(opener.objMapControl, object, opener.globalClientManager.clientsList);
                ClientManager.loadClientsDataSource(getClientGrid(), opener.globalClientManager.clientsList, opener.globalClientManager.clientsDataSource);
                responseEnd(getrpvClientManagerUpdateControl());
            }

            function getClientsByCompanyAndClientGroupIDError(error) {
                responseEnd(getrpvClientManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
            }

            function ClientGrid_RowSelecting(sender, args) {
                ClientManager.clientGridRowSelecting(opener, args, getCkbZoomClient().checked, getCkbCenterClient().checked);
            }

            function ClientGrid_OnRowClick(sender, args) {
                if (ClientManager.clientGridOnRowClick(opener, args)) {
                    ClientDeleteCompletely();
                }

            }

            function ClientDeleteCompletely() {
                requestStart(getrpvClientManagerUpdateControl());
                getClientGrid().clearSelectedItems();

                if (opener.globalClientManager.clientID != -1) {
                    PageMethods.wsClientDelete(opener.globalClientManager.clientGroupID, opener.globalClientManager.clientID, ClientDeleteCompletelyOk, ClientDeleteCompletelyError);
                }
                else {
                    responseEnd(getrpvClientManagerUpdateControl());
                    objWindowsMessageManager.show_Warning("Debe seleccionar un cliente para eliminarlo.", titles.clientTitle);
                }
            }

            function ClientDeleteCompletelyOk(object) {
                if (object = "true") {
                    ClientManager.refreshAfterDeleteClient(opener, getClientGrid());
                    responseEnd(getrpvClientManagerUpdateControl());
                    objWindowsMessageManager.show_Info("Se eliminó correctamente el cliente.", titles.clientTitle);
                }
                else {
                    responseEnd(getrpvClientManagerUpdateControl());
                    objWindowsMessageManager.show_Error("No se eliminó correctamente el cliente.", titles.clientTitle);
                }
            }

            function ClientDeleteCompletelyError(error) {
                responseEnd(getrpvClientManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
            }

            function ClientGrid_RowDeselecting(sender, args) {
                var index = ClientManager.getIndexClientID(opener.globalClientManager.clientsList, args.getDataKeyValue("ClientID"));
                if (index != -1) {
                    opener.globalClientManager.clientsList[index].checked = false;
                    ClientManager.showAllClientsChecked(opener.globalClientManager.clientsList);
                }
            }

            

            function getClientsGroupsByUser() {
                PageMethods.wsGetClientsGroupsByUsername(getClientsGroupsByUserOk, getClientsGroupsByUserError);
            }

            
            function loadClientsGroupsDataSourceWait(){
                ClientManager.loadClientsGroupsDataSource(getClientsGroupsGrid(), opener.globalClientManager.clientsGroupsList, opener.globalClientManager.clientsGroupsDataSource);
                responseEnd(getrpvClientManagerUpdateControl());
            }

            function getClientsGroupsByUserOk(object) {
                requestStart(getrpvClientManagerUpdateControl());
                ClientManager.openXMLClientsGroupsByUsername(object, opener.globalClientManager.clientsGroupsList);
                setTimeout(loadClientsGroupsDataSourceWait, 10);
            }

            function getClientsGroupsByUserError(error) {
                responseEnd(getrpvClientManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
            }

            function getrpvClientManagerUpdateControl() {
                return "<%=  rpvClientManager.ClientID %>";
            }

            function enableDisableClientEventClickMap() {
                ClientManager.enableDisableClientEventClickMap(opener, getCkbClient().checked);
            }

            function getRtbClientName() {
                return $get('<%= rtbClientName.ClientID %>');
            }

            function getRtbTel() {
                return $get('<%= rtbTel.ClientID %>');
            }

            function getRtbEmail() {
                return $get('<%= rtbEmail.ClientID %>');
            }

            function getCkbClient() {
                return $get('<%= ckbClient.ClientID %>');
            }

            function getCkbZoomClient() {
                return $get('<%= ckbZoomClient.ClientID %>');
            }

            function getCkbCenterClient() {
                return $get('<%= ckbCenterClient.ClientID %>');
            }

            function requestStart(object) {
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").show(object);
                }
                catch (e) {
                    null;
                }
            }

            function responseEnd(object) {
                try {
                    $find("<%= RadAjaxLoadingPanel1.ClientID%>").hide(object);
                }
                catch (e) {
                    null;
                }
            }

            function isValidToInsertClient() {
                requestStart(getrpvClientManagerUpdateControl());
                var objects = { clientName: getRtbClientName().value, lat: null, lng: null }
                if (ClientManager.isValidToInsertClient(opener, objects)) {
                    ClientInsert(objects);
                }
                else {
                    responseEnd(getrpvClientManagerUpdateControl());
                }
            }

            function ClientInsert(objects) {
                PageMethods.wsClientInsert(opener.globalClientManager.companyID, opener.globalClientManager.clientGroupID, objects.clientName, objects.lat, objects.lng, getRtbTel().value, getRtbEmail().value, ClientInsertOk, ClientInsertError);
            }

            function ClientInsertOk(id) {
                if (id != -1) {
                    ClientManager.clientInsertSuccessful(opener, id, getClientGrid(), getRtbClientName().value);
                    responseEnd(getrpvClientManagerUpdateControl());
                    getRtbClientName().value = "";
                    getRtbTel().value = "";
                    getRtbEmail().value = "";
                    objWindowsMessageManager.show_Info("Se registró correctamente el Cliente.", titles.clientTitle);
                }
                else {
                    responseEnd(getrpvClientManagerUpdateControl());
                    objWindowsMessageManager.show_Warning("El nombre del cliente ya está registrado para esta compañía, cambiar el nombre del cliente.", titles.clientTitle);
                }
            }

            function ClientInsertError(error) {
                responseEnd(getrpvClientManagerUpdateControl());
                objWindowsMessageManager.show_Error(error.get_message(), titles.clientTitle);
            }

        </script>
    </telerik:RadScriptBlock>
    <style type="text/css">
        .auto-style1
        {
            width: 153px;
        }
    </style>
</head>
<body onload="getCompaniesByAdminUsername()">

    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true"></telerik:RadScriptManager>
        <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
            <AjaxSettings>
					<telerik:AjaxSetting AjaxControlID="AjaxControlID1">
						<UpdatedControls>
							<telerik:AjaxUpdatedControl ControlID="Loading" LoadingPanelID="RadAjaxLoadingPanel1" />
						</UpdatedControls>
					</telerik:AjaxSetting>
				</AjaxSettings>
        </telerik:RadAjaxManager>

        <telerik:RadTabStrip ID="rtsClientManager" runat="server" SelectedIndex="0" MultiPageID="rmpClientManager" >
        </telerik:RadTabStrip>
        <telerik:RadMultiPage ID="rmpClientManager" runat="server"  SelectedIndex="0">
            <telerik:RadPageView ID="rpvClientManager" runat="server">

                <table style="width: 100%; text-align: left">
		             <tr>
                        <td colspan="3">
                            <fieldset>
								<legend>Nuevo Cliente</legend>
								<table class="auto-style2">
									<tr>
										<td class="auto-style1">
											<asp:CheckBox ID="ckbClient" runat="server" onclick="javascript:enableDisableClientEventClickMap()" Text="Habilitar Marcadores" Width="150px"/>
                                            <asp:CheckBox ID="ckbZoomClient" runat="server" Text="Acercar Parada" Width="150px"/>
                                            <asp:CheckBox ID="ckbCenterClient" runat="server" Text="Centrar Parada" Width="150px"/>
										</td>
									
										<td>Nombre:</td>
										<td>
											<telerik:RadTextBox ID="rtbClientName" runat="server" AutoPostBack="false">
											</telerik:RadTextBox>
										</td>
									    <td>Teléfono:</td>
										<td>
											<telerik:RadTextBox ID="rtbTel" runat="server" Width="97px" AutoPostBack="false">
											</telerik:RadTextBox>
										</td>
                                        <td>Email:</td>
										<td>
											<telerik:RadTextBox ID="rtbEmail" runat="server" Width="139px" AutoPostBack="false" EnableViewState="False">
											</telerik:RadTextBox>
										</td>
										<td>&nbsp;&nbsp;&nbsp;&nbsp;</td>
										<td>
											<input id="btnSaveClient" type="button" value="Guardar Cliente" onclick="isValidToInsertClient();" />
										</td>
									</tr>
								</table>
                            </fieldset>
                        </td>
                    </tr>
                    <tr>
                        <td>
                  
				            <fieldset>
					            <legend>Compañias Registradas</legend>
					            <telerik:RadGrid ID="rgCompaniesGrid" runat="server" AllowMultiRowSelection="False" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" OnNeedDataSource="rgCompaniesGrid_NeedDataSource"  Width="250px">
						            <ClientSettings>
							            <Selecting AllowRowSelect="True" />
							            <ClientEvents OnRowClick="CompaniesGrid_OnRowClick" />
							            <Scrolling AllowScroll="True" UseStaticHeaders="true" />
						            </ClientSettings>
						            <MasterTableView EditMode="PopUp" EditFormSettings-PopUpSettings-Modal="true" EditFormSettings-CaptionFormatString="Modo Edición" ClientDataKeyNames="CompanyID" NoMasterRecordsText="No hay compañias registradas">
							            <CommandItemSettings ExportToPdfText="Export to PDF" />
							            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
							            </RowIndicatorColumn>
							            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
							            </ExpandCollapseColumn>
							            <Columns>
								            <telerik:GridBoundColumn DataField="CompanyID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="CompanyID" Display="false">
								            </telerik:GridBoundColumn>
								            <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre" Visible="true">
								            </telerik:GridBoundColumn>
							            </Columns>
							            <EditFormSettings>
								            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
								            </EditColumn>
							            </EditFormSettings>
						            </MasterTableView>
						            <FilterMenu EnableImageSprites="true">
						            </FilterMenu>
					            </telerik:RadGrid>
				            </fieldset>
			            </td>
			            <td>
                  
				            <fieldset>
					            <legend>Grupos de Clientes Registrados</legend>
					            <telerik:RadGrid ID="rgClientsGroupsGrid" runat="server" AllowMultiRowSelection="False" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" OnNeedDataSource="rgClientsGroupsGrid_NeedDataSource"  Width="250px">
						            <ClientSettings>
							            <Selecting AllowRowSelect="True" />
							            <ClientEvents OnRowClick="ClientsGroupsGrid_OnRowClick" />
							            <Scrolling AllowScroll="True" UseStaticHeaders="true" />
						            </ClientSettings>
						            <MasterTableView EditMode="PopUp" EditFormSettings-PopUpSettings-Modal="true" EditFormSettings-CaptionFormatString="Modo Edición" ClientDataKeyNames="ClientGroupID" NoMasterRecordsText="No hay grupos de clientes registrados">
							            <CommandItemSettings ExportToPdfText="Export to PDF" />
							            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
							            </RowIndicatorColumn>
							            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
							            </ExpandCollapseColumn>
							            <Columns>
								            <telerik:GridBoundColumn DataField="ClientGroupID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="ClientGroupID" Display="false">
								            </telerik:GridBoundColumn>
								            <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre" Visible="true">
								            </telerik:GridBoundColumn>
							            </Columns>
							            <EditFormSettings>
								            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
								            </EditColumn>
							            </EditFormSettings>
						            </MasterTableView>
						            <FilterMenu EnableImageSprites="true">
						            </FilterMenu>
					            </telerik:RadGrid>
				            </fieldset>
			            </td>
			           <td>
                           <fieldset>
					            <legend>Clientes Registrados</legend>
                           <telerik:RadGrid ID="rgClientsGrid" runat="server" AllowMultiRowSelection="True" AutoGenerateColumns="False" CellSpacing="0" GridLines="None" Height="100px" OnNeedDataSource="rgClientsGrid_NeedDataSource"  Width="250px">
                                <ClientSettings>
							            <Selecting AllowRowSelect="True" />
							            <ClientEvents OnRowClick="ClientGrid_OnRowClick" OnRowDeselecting="ClientGrid_RowDeselecting" OnRowSelecting="ClientGrid_RowSelecting" />
							            <Scrolling AllowScroll="True" UseStaticHeaders="true" />
						            </ClientSettings>
						            <MasterTableView EditMode="PopUp" EditFormSettings-PopUpSettings-Modal="true" EditFormSettings-CaptionFormatString="Modo Edición" ClientDataKeyNames="ClientID" NoMasterRecordsText="No hay clientes registrados">
							            <CommandItemSettings ExportToPdfText="Export to PDF" />
							            <RowIndicatorColumn FilterControlAltText="Filter RowIndicator column" Visible="True">
							            </RowIndicatorColumn>
							            <ExpandCollapseColumn FilterControlAltText="Filter ExpandColumn column" Visible="True">
							            </ExpandCollapseColumn>
							            <Columns>
								            <telerik:GridImageColumn ImageUrl="..\..\Template\Icons\16px\Delete.gif" UniqueName="DeleteColumn" ItemStyle-Width="40px" HeaderStyle-Width="40px">
								            </telerik:GridImageColumn>
								            <telerik:GridBoundColumn DataField="ClientID" FilterControlAltText="Filter Description column" HeaderText="ID" UniqueName="ClientID" Display="false">
								            </telerik:GridBoundColumn>
								            <telerik:GridBoundColumn DataField="Name" FilterControlAltText="Filter Description column" HeaderText="Nombre" Visible="true" ItemStyle-Width="150px" HeaderStyle-Width="150px">
								            </telerik:GridBoundColumn>
								            <telerik:GridClientSelectColumn HeaderText="Mostrar" UniqueName="chkShowClient">
								            </telerik:GridClientSelectColumn>
							            </Columns>
							            <EditFormSettings>
								            <EditColumn FilterControlAltText="Filter EditCommandColumn column">
								            </EditColumn>
							            </EditFormSettings>
						            </MasterTableView>
						            <FilterMenu EnableImageSprites="true">
						            </FilterMenu>

                           </telerik:RadGrid>
                           </fieldset>
                       </td>
		            </tr>
	            </table>
            </telerik:RadPageView>
        </telerik:RadMultiPage>
          
        <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" Skin="Default"></telerik:RadAjaxLoadingPanel>
    </form>
</body>
</html>
